package rmi;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import client.Client;

public class MessageRemote {
    private Context ctx=null;
    private ServeurRmiInterface serv;
    
    public MessageRemote()
    {
    	init();
    }
    
    public void init()
    {			
 	    // Set properties
    	Hashtable<String,String> env = new Hashtable<String,String>(11);
 		    
	    // Definition of the jndi server
    	env.put(Context.INITIAL_CONTEXT_FACTORY,
 			    "com.sun.jndi.rmi.registry.RegistryContextFactory");
 	    env.put(Context.PROVIDER_URL, "rmi://localhost:2999");
 		    
 	    // Get the initial context
	    try {
	    	
	    	ctx = new InitialContext(env);
	    	serv =(ServeurRmiInterface) getCtx().lookup("serveur");
	    	
	    	
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
    
    public Context getCtx() {
		return ctx;
	}
    
	public void setCtx(Context ctx) {
		this.ctx = ctx;
	}
	
	public void sendMessage(Message msg,int flag)
	{
		 try {

			serv.envMsg(msg,flag);
			 
			} catch (RemoteException e) {
		
				e.printStackTrace();
			}
	}
	

	public int enregistre(Client cl)
	{
		int i = 0; 
		try {

			i = serv.enregistreClient(cl);
			 
			} catch (RemoteException e) {
		
				e.printStackTrace();
			}
		return i;
	}

	public ArrayList<Message> recvMessage()
	{
		ArrayList<Message> listMsg = new ArrayList<Message>();
		 try {
			
			 listMsg = serv.recvMsg();
			 
			} catch (RemoteException e) {
		
				e.printStackTrace();
			}
		return listMsg;
	}
	

	
	public String getPro()
	{
		String pro =null;
		try {
			
			pro = serv.getPro();
			 
			} catch (RemoteException e) {
		
				e.printStackTrace();
			}
		return pro;
	}
	public void quit()
	{
			try {
					
				 	serv.quit();
			 
			} catch (RemoteException e) {
		
				e.printStackTrace();
			} 
	}
	
}
